package com.originskyseed.platform.user.controller;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.common.api.constant.RedisKeyConstans;
import com.originskyseed.platform.common.api.constant.RedisOperateEnum;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.redis.util.RedisUtil;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.OrgGovernment;
import com.originskyseed.platform.user.service.IOrgGovernmentService;
import com.originskyseed.platform.user.vo.request.OrgGovernmentRequestVO;

/**
 * 行政区划表Controller类（OSI_org_government）
 *
 * @author LiChengHuan
 */
@Controller
@RequestMapping("/orgGovernment")
@BaseLocaleResource(localeFileName = "i18n_user")
public class OrgGovernmentController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(OrgGovernmentController.class);

	@DubboReference
	private IOrgGovernmentService orgGovernmentService;

	/**
	 * 行政区划列表页面
	 *
	 * @return
	 */
	@RequestMapping("/orgGovernmentList.html")
	public ModelAndView orgGovernmentList() {
		return new ModelAndView("org_government/org_government_list");
	}

	@ResponseBody
	@RequestMapping("/orgGovernmentView.json")
	@RequiredParams(names = { "id" })
	public BaseResponseBody orgGovernmentView(HttpServletRequest request) {
		BaseResponseBody result = null;
		OrgGovernment orgGovernment = null;
		try {
			String id = this.getParameterString("id", null);
			if (StringUtils.isNotBlank(id)) {
				orgGovernment = this.orgGovernmentService.selectByPrimaryKey(id);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), orgGovernment);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 加载一级行政区划树
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectOneLevenTree.json")
	public BaseResponseBody selectOneLevenTree(HttpServletRequest request) {
		BaseResponseBody result = null;
		JSONArray jsonArray = null;
		try {
			// 从缓存中获取值
			jsonArray = (JSONArray) RedisUtil.getInstance().getForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_PROVINCE), "0");
			// 判断缓存是否存在
			if (ObjectUtils.isEmpty(jsonArray)) {
				jsonArray = this.orgGovernmentService.selectGovernmentByLevel("1");
				// 添加到Redis缓存，key为parentCode
				RedisUtil.getInstance().putForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_PROVINCE), "0", jsonArray);
			}

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", "0");
			jsonObject.put("parentCode", null);
			jsonObject.put("countryCode", null);
			jsonObject.put("levelId", 0);
			jsonObject.put("code", "0");
			jsonObject.put("sequence", "00");
			jsonObject.put("name", "中国");
			jsonObject.put("open", false);
			jsonArray.add(jsonObject);

			Resequence(jsonArray);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), jsonArray);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 加载一级行政区列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectOneLevelList.json")
	public BaseResponseBody selectOneLevelList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			OrgGovernment orgGovernment = new OrgGovernment();
			orgGovernment.setParentCode("0");
			orgGovernment.setStatus(1);
			List<OrgGovernment> orgGovernmentList = this.orgGovernmentService.selectList(orgGovernment);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), orgGovernmentList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 按照优先级排序
	 * 
	 * @param jsonArray
	 * @return
	 */
	private void Resequence(JSONArray jsonArray) {
		// 根据优先级排序
		Collections.sort(jsonArray, (s1, s2) -> {
			if (StringUtils.isBlank(((JSONObject) s2).getString("sequence")) || StringUtils.isBlank(((JSONObject) s1).getString("sequence")))
				((JSONObject) s1).put("sequence", " ");
			return ((JSONObject) s1).getString("sequence").compareTo(((JSONObject) s2).getString("sequence"));
		});
	}

	/**
	 * 根据code查询行政区划树
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectTreeByParentCode.json")
	public BaseResponseBody selectTreeByParentCode(HttpServletRequest request) {
		BaseResponseBody result = null;
		JSONArray jsonArray = null;
		try {
			String parentCode = this.getParameterString("parentCode", null);
			// 从Redis获取值
			jsonArray = (JSONArray) RedisUtil.getInstance().getForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_PROVINCE), parentCode);
			// 判断这个值是否存在
			if (ObjectUtils.isEmpty(jsonArray)) {
				jsonArray = this.orgGovernmentService.selectGovernmentByParentCode(parentCode);
				// 添加值到Redis
				RedisUtil.getInstance().putForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_PROVINCE), parentCode, jsonArray);
			}
			Resequence(jsonArray);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), jsonArray);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 加载行政区划树
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/orgGovernmentTree.json")
	public BaseResponseBody orgGovernmentTree(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			JSONArray orgGovernmentTree = this.orgGovernmentService.selectUserOrgTree();
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), orgGovernmentTree);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改行政区划显示状态（启用、禁用）
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateorgGovernment.json")
	@RequiredParams(names = { "id", "status" })
	public BaseResponseBody updateCarousel(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			OrgGovernment orgGovernment = this.getParameterBean(OrgGovernment.class);
			this.orgGovernmentService.updateByPrimaryKeySelective(orgGovernment);

			// 更新Redis的值
			updateAndDeleteRedis(this.orgGovernmentService.selectJSONObjectById(orgGovernment.getId()), RedisOperateEnum.UPDATE.name());

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/orgGovernmentList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody orgGovernmentList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			OrgGovernmentRequestVO requestVO = this.getParameterBean(OrgGovernmentRequestVO.class);

			// 分页查询
			BasePage<OrgGovernment> page = new BasePage<OrgGovernment>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.orgGovernmentService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/orgGovernmentSave.json")
	public BaseResponseBody orgGovernmentSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			OrgGovernment orgGovernment = this.getParameterBean(OrgGovernment.class);
			if (this.orgGovernmentService.existCode(orgGovernment)) {
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.CODE_EXIST_ERROR.getMsg()), null);
			} else {
				if (StringUtils.isNotBlank(orgGovernment.getId())) {
					JSONObject jsonObject = this.orgGovernmentService.updateByPrimaryKeySelective(orgGovernment);
					// 更新Redis的值
					updateAndDeleteRedis(jsonObject, RedisOperateEnum.UPDATE.name());
				} else {
					JSONObject jsonObject = this.orgGovernmentService.insertSelective(orgGovernment);
					// 添加值到Redis中
					RedisUtil.getInstance().putForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_PROVINCE), orgGovernment.getParentCode(), jsonObject);
				}
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), orgGovernment);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 更新和删除共同操作Redis的方法
	 * 
	 * @param jsonObject
	 */
	private void updateAndDeleteRedis(JSONObject jsonObject, String method) {
		// 从Redis获取值
		JSONArray jsonArray = (JSONArray) RedisUtil.getInstance().getForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_PROVINCE), jsonObject.getString("parentCode"));
		if (!ObjectUtils.isEmpty(jsonArray)) {
			for (int i = 0; i < jsonArray.size(); i++) {
				if (StringUtils.equals(jsonObject.getString("id"), jsonArray.getJSONObject(i).getString("id"))) {
					// 修改行政区域的状态
					jsonArray.remove(i);
					// 添加到JSONArray
					if (RedisOperateEnum.UPDATE.name().equals(method)) {
						jsonArray.add(jsonObject);
					}
					// 保存到Redis中
					RedisUtil.getInstance().putForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_PROVINCE), jsonObject.getString("parentCode"), jsonArray);
					break;
				}
			}
		}
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/orgGovernmentDelete.json")
	@RequiredParams(names = { "ids" })
	public BaseResponseBody orgGovernmentDelete(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			for (String id : ids) {
				OrgGovernment orgGovernment = this.orgGovernmentService.selectByPrimaryKey(id);
				// 获取JSONObject为Redis
				JSONObject jsonObject = this.orgGovernmentService.selectJSONObjectById(id);
				if (this.orgGovernmentService.selectExitChild(orgGovernment)) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), null);
				}
				// 从Redis删除行政区域
				updateAndDeleteRedis(jsonObject, RedisOperateEnum.DELETE.name());
			}
			this.orgGovernmentService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}